<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="10">
        <el-col :span="8">
          <!-- 输入框 -->
          <el-input placeholder="请输入内容" v-model="getUserData.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 按钮 -->
          <el-button type="primary" @click="addUserVisible">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userData" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="showDeleteDialog(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"          
            >
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showAlllotRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getUserData.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="getUserData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      ref="addFormRef"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserPost">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm">
        <el-form-item label="用户名" label-width="70px">
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="70px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="70px">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserPut">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRolesDialogVisible" width="50%" @close="setRolesDialogClosed" >
      <div>
        <p>当前的用户:　{{userInfo.username}}</p>
        <p>当前的角色:　{{userInfo.role_name}}</p>
        <p>当前的用户:  <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in roleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
          >
        </el-option>
        </el-select>
      </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRolesPut">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询用户列表的数据
      getUserData: {
        // 查询用户的参数
        query: "",
        // 查询的页数
        pagenum: 1,
        // 每页的显示的条数
        pagesize: 2
      },
      userData: [],
      total: 0,
      // 控制添加用户面板的显示和隐藏
      addDialogVisible: false,
      // 添加用户的数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 添加用户的校验规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名的长度在3~10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名的长度在6~15个字符之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { trigger: "blur" }
        ]
      },
      // 控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      // 编辑用户的数据
      editForm: {},
      // 控制分配角色对话框的显示和隐藏
      setRolesDialogVisible: false,
      // 当前点击用户的信息
      userInfo: {},
      // 角色列表
      roleList: [],
      // 已选择的角色id
      selectedRoleId: '',

    };
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.getUserData
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.userData = res.data.users;
      this.total = res.data.total;
    },
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      this.getUserData.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值的改变
    handleCurrentChange(newPage) {
      this.getUserData.pagenum = newPage;
      this.getUserList();
    },
    // 监听用户状态的改变
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        // 将双向数据绑定的值改为数据库的数据
        userInfo.mg_state = !userInfo.mg_state;
        // 提示信息
        this.$message.error("用户状态修改失败!");
      } else {
        this.$message.success("状态修改成功");
      }
    },
    // 点击按钮显示添加用户面板
    addUserVisible() {
      this.addDialogVisible = true;
    },
    // 监听关闭窗口的事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户
    addUserPost() {
      this.$refs.addFormRef.validate(async valid => {
        // 校验规则不过关, 直接return
        if (!valid) return;
        // 可以发送添加用户的网络请求
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        // 隐藏添加用户的面板
        this.addDialogVisible = false;
        // 重新渲染用户列表数据
        this.getUserList();
      });
    },

    // 点击按钮显示修改用户窗口
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`users/${id}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;

      // 显示编辑用户对话框
      this.editDialogVisible = true;
    },

    // 修改用户信息
    async editUserPut() {
      // console.log(this.editForm);
      // 结构对象得到 用户的eamil 和 mobile 信息
      const { email, mobile } = this.editForm;
      const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
        email,
        mobile
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // 重新渲染页面
      this.getUserList();
      // 提示信息
      this.$message.success("编辑用户成功!");
      // 关闭窗口
      this.editDialogVisible = false;
    },

    // 点击按钮显示删除用户对话框
    async showDeleteDialog(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(error => error);
      if (confirmResult !== "confirm") {
        return this.$message.warning("已取消删除");
      }
      const { data: res } = await this.$http.delete(`users/${id}`);
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      this.getUserList();
    },

    // 点击按钮显示分配角色对话框
    async showAlllotRoles(userInfo) {
      this.userInfo = userInfo;
      this.setRolesDialogVisible = true;
      const {data: res} = await this.$http.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.roleList = res.data;
    },

    // 点击确定给用户分配角色
    async allotRolesPut() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色!');
      }
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, {rid: this.selectedRoleId});
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success(res.meta.msg);
      this.getUserList();
      this.setRolesDialogVisible = false;
    },
    
    // 监听关闭对话框
    setRolesDialogClosed() {
      this.roleList = [];
      this.selectedRoleId = '';
    }
  },
  
  created() {
    this.getUserList();
  }
};
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 10px;
}
</style>